package com.pk.platform.util.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pk.platform.domain.privilege.User;
import com.pk.platform.util.GlobalLoader;
import com.pk.platform.util.constant.Constant;

public class PrivilegeFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		User user = (User)req.getSession().getAttribute(Constant.USER);
		Map<String, String> actionMap = (Map<String, String>)GlobalLoader.getContext().getAttribute(Constant.ACTION_MAP);
		String loginUrl = req.getContextPath() + "/user/toLogin.action";
		try
		{
			if(user != null)
			{
				SystemContext.setUser(user);
				Map<String, String> privilegeMap = user.getPrivilege();
				String action = req.getServletPath().substring(1);
				int index = action.indexOf("?");
				if(index > -1)
				{
					action = action.substring(0, index);
				}
				if(actionMap.get(action) != null && privilegeMap.containsValue(action) == false)
				{
					res.sendRedirect(loginUrl);
				}
				chain.doFilter(request, response);
			}
			else
			{
				res.sendRedirect(loginUrl);
			}
		}
		finally
		{
			SystemContext.removeUser();
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
	
}
